home *** CD-ROM | disk | FTP | other *** search
- Path: news.sprintlink.net!datalytics!news
- From: Rob Stewart <stew@datalytics.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Purpose of constructor initializer list?
- Date: 4 Jan 1996 17:36:36 GMT
- Organization: Datalytics, Inc
- Message-ID: <4ch374$ldg@gold.datalytics.com>
- References: <EMERICK.95Dec9130521@csa.bu.edu> <4brblp$h1r@news.puug.pt>
- NNTP-Posting-Host: pc071.datalytics.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.22 (Windows; I; 32bit)
-
- In article <EMERICK.95Dec9130521@csa.bu.edu>
- emerick@csa.bu.edu (Emerick Rogul) writes:
-
- >
- >
- > I'm confused about why and when one should use the constructor
- > initializer list. I understand that when I derive a new class that's
- > how I initialize the base class. But in many examples, it seems the
- > initializer list is used to initialize the derived class also. Is
- > there any benefit to initializing the class in the initializer list
- > rather than simply in the constructor?
-
- The benefit is one of performance. Without an initializer
- list, the compiler will initialize all data members (dms) in
- the class before invoking the c'tor body. For objects,
- default construction can be trivial or expensive. After this
- initialization, the c'tor body must assign values to these
- dms, so you then invoke the assignment operator on objects.
- For many classes, this can mean undoing what the default c'tor
- did, then assigning the new value.
-
- For built-in types, this is moot. The compiler doesn't
- initialize non-static variables. But, since you never know
- when a dm will change types (perhaps you've added a class to
- handle the counter behavior and use that class in place of
- size_t for a counter variable), and for consistency with all
- other dms, you should initialize all dms.
-
- > Is it an attempt to make the
- > constructor empty?
-
- Using an initializer list, by definition, does not make for an
- empty c'tor. The initializer list is part of the c'tor's
- code.
-
- >
- > Thanks,
- > Emerick Rogul
- > emerick@cs.bu.edu
-
- --
- Robert Stewart | My opinions are usually my own.
- Datalytics, Inc.
- (513)226-7700
- stew@datalytics.com
-
-
-